/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.gianluca.sagrafx.entities;

import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import org.gianluca.sagrafx.entities.exceptions.NonexistentEntityException;
import org.gianluca.sagrafx.entities.exceptions.PreexistingEntityException;

/**
 *
 * @author eginfer
 */
public class PietanzeJpaController implements Serializable {

    public PietanzeJpaController(EntityManagerFactory emf) {
        this.emf = emf;
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Pietanze pietanze) throws PreexistingEntityException, Exception {
        if (pietanze.getOrdiniCollection() == null) {
            pietanze.setOrdiniCollection(new ArrayList<Ordini>());
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Collection<Ordini> attachedOrdiniCollection = new ArrayList<Ordini>();
            for (Ordini ordiniCollectionOrdiniToAttach : pietanze.getOrdiniCollection()) {
                ordiniCollectionOrdiniToAttach = em.getReference(ordiniCollectionOrdiniToAttach.getClass(), ordiniCollectionOrdiniToAttach.getId());
                attachedOrdiniCollection.add(ordiniCollectionOrdiniToAttach);
            }
            pietanze.setOrdiniCollection(attachedOrdiniCollection);
            em.persist(pietanze);
            for (Ordini ordiniCollectionOrdini : pietanze.getOrdiniCollection()) {
                Pietanze oldIdPietanzaOfOrdiniCollectionOrdini = ordiniCollectionOrdini.getIdPietanza();
                ordiniCollectionOrdini.setIdPietanza(pietanze);
                ordiniCollectionOrdini = em.merge(ordiniCollectionOrdini);
                if (oldIdPietanzaOfOrdiniCollectionOrdini != null) {
                    oldIdPietanzaOfOrdiniCollectionOrdini.getOrdiniCollection().remove(ordiniCollectionOrdini);
                    oldIdPietanzaOfOrdiniCollectionOrdini = em.merge(oldIdPietanzaOfOrdiniCollectionOrdini);
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            if (findPietanze(pietanze.getId()) != null) {
                throw new PreexistingEntityException("Pietanze " + pietanze + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Pietanze pietanze) throws NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Pietanze persistentPietanze = em.find(Pietanze.class, pietanze.getId());
            Collection<Ordini> ordiniCollectionOld = persistentPietanze.getOrdiniCollection();
            Collection<Ordini> ordiniCollectionNew = pietanze.getOrdiniCollection();
            Collection<Ordini> attachedOrdiniCollectionNew = new ArrayList<Ordini>();
            for (Ordini ordiniCollectionNewOrdiniToAttach : ordiniCollectionNew) {
                ordiniCollectionNewOrdiniToAttach = em.getReference(ordiniCollectionNewOrdiniToAttach.getClass(), ordiniCollectionNewOrdiniToAttach.getId());
                attachedOrdiniCollectionNew.add(ordiniCollectionNewOrdiniToAttach);
            }
            ordiniCollectionNew = attachedOrdiniCollectionNew;
            pietanze.setOrdiniCollection(ordiniCollectionNew);
            pietanze = em.merge(pietanze);
            for (Ordini ordiniCollectionOldOrdini : ordiniCollectionOld) {
                if (!ordiniCollectionNew.contains(ordiniCollectionOldOrdini)) {
                    ordiniCollectionOldOrdini.setIdPietanza(null);
                    ordiniCollectionOldOrdini = em.merge(ordiniCollectionOldOrdini);
                }
            }
            for (Ordini ordiniCollectionNewOrdini : ordiniCollectionNew) {
                if (!ordiniCollectionOld.contains(ordiniCollectionNewOrdini)) {
                    Pietanze oldIdPietanzaOfOrdiniCollectionNewOrdini = ordiniCollectionNewOrdini.getIdPietanza();
                    ordiniCollectionNewOrdini.setIdPietanza(pietanze);
                    ordiniCollectionNewOrdini = em.merge(ordiniCollectionNewOrdini);
                    if (oldIdPietanzaOfOrdiniCollectionNewOrdini != null && !oldIdPietanzaOfOrdiniCollectionNewOrdini.equals(pietanze)) {
                        oldIdPietanzaOfOrdiniCollectionNewOrdini.getOrdiniCollection().remove(ordiniCollectionNewOrdini);
                        oldIdPietanzaOfOrdiniCollectionNewOrdini = em.merge(oldIdPietanzaOfOrdiniCollectionNewOrdini);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = pietanze.getId();
                if (findPietanze(id) == null) {
                    throw new NonexistentEntityException("The pietanze with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Pietanze pietanze;
            try {
                pietanze = em.getReference(Pietanze.class, id);
                pietanze.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The pietanze with id " + id + " no longer exists.", enfe);
            }
            Collection<Ordini> ordiniCollection = pietanze.getOrdiniCollection();
            for (Ordini ordiniCollectionOrdini : ordiniCollection) {
                ordiniCollectionOrdini.setIdPietanza(null);
                ordiniCollectionOrdini = em.merge(ordiniCollectionOrdini);
            }
            em.remove(pietanze);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Pietanze> findPietanzeEntities() {
        return findPietanzeEntities(true, -1, -1);
    }

    public List<Pietanze> findPietanzeEntities(int maxResults, int firstResult) {
        return findPietanzeEntities(false, maxResults, firstResult);
    }

    private List<Pietanze> findPietanzeEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Pietanze.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Pietanze findPietanze(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Pietanze.class, id);
        } finally {
            em.close();
        }
    }

    public int getPietanzeCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Pietanze> rt = cq.from(Pietanze.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
